package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CaiPinListTask;
import com.xgkj.diyiketang.task.ChuangJianYueFanTask;
import com.xgkj.diyiketang.task.HuoQuJianGeTask;
import com.xgkj.diyiketang.util.DateTimePickDialogUtil;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by XCKJ_Paladowow on 2016/4/13.
 */
public class ChuangJianHuoDongActivity extends BaseActivity implements View.OnClickListener{
    private Context mContext;
    private int jiangeTaskId = -1;
    private int createTaskId = -1;
    private RelativeLayout mStartLayout;
    private EditText mStartTime;
    private RelativeLayout mQiangDanLayout;
    private EditText mQiangDanEdit;
    private String initDateTime = "2016年05月12日 11:00"; //= "2016年4月29日 11:00"; // 初始化开始时间
    private Button mSubmit;
    private RelativeLayout mCityLayout;
    private TextView mCityText;
    private String city;

    private RelativeLayout mShangQuanLayout;
    private TextView mShangQuanText;
    private String shangquan;
    private String shangquanId ="";

    //private RelativeLayout mShangjiaLayout;
    //private TextView mShangjiaText;
    //private String shangjia;

    private RelativeLayout mXingbieLayout;
    private TextView mSexText;
    private String sexLimtit;
    private PopupWindow sexPopWindow;

//    private RelativeLayout mTuiChuLayout;
//    private TextView mTuiChuText;
//    private String tuichu;
//    private PopupWindow tcPopWindow;
    private TextView mJieZhiText;
    private String mDateCha;
    private EditText mTitleText;
    private String mTitle;
    private String mJiezhiTime;
    private String mKaishiTime;
    private String mQiangDanTime;
    private String shangjiaId;
    private EditText mRenShuText;
    private String mRenshu;
//    private EditText mFeiYongText;
//    private String mFeiyong;
    private EditText mDescText;
    private String mDesc;
    private TextView mBack;

//    private RelativeLayout mCaipinLayout;
//    private String selectCaipin;
//    private String mCaipinString;
//    private TextView mCaipinText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chuangjianhuodong);
        mContext = this;
        initView();

    }

    private void initView(){
        mBack = (TextView) findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });



        mStartLayout = (RelativeLayout) findViewById(R.id.starttime_layout);
        mStartTime = (EditText) findViewById(R.id.starttime_content);
        mStartLayout.setOnClickListener(this);

        mQiangDanLayout = (RelativeLayout) findViewById(R.id.qiangdantime_layout);
        mQiangDanEdit = (EditText) findViewById(R.id.qiangdantime_content);
        mQiangDanLayout.setOnClickListener(this);

        mSubmit = (Button) findViewById(R.id.submit_btn);
        mSubmit.setOnClickListener(this);
        mCityLayout = (RelativeLayout) findViewById(R.id.suozaicity_layout);
        mCityLayout.setOnClickListener(this);
        mCityText = (TextView) findViewById(R.id.suozaicity_content);

        mShangQuanLayout = (RelativeLayout) findViewById(R.id.suozaishangquan_layout);
        mShangQuanLayout.setOnClickListener(this);
        mShangQuanText = (TextView) findViewById(R.id.suozaishangquan_content);

//        mShangjiaLayout = (RelativeLayout) findViewById(R.id.hd_shangjia_layout);
//        mShangjiaLayout.setOnClickListener(this);
//        mShangjiaText = (TextView) findViewById(R.id.hd_shangjia_content);

        mXingbieLayout = (RelativeLayout) findViewById(R.id.hd_xingbie_layout);
        mXingbieLayout.setOnClickListener(this);
        mSexText = (TextView) findViewById(R.id.hd_xingbie_content);
//        mCaipinLayout = (RelativeLayout) findViewById(R.id.hd_caipin_layout);
//        mCaipinLayout.setOnClickListener(this);
//        mCaipinText = (TextView) findViewById(R.id.hd_caipin_content);
        initSexPopWindow();
//
//        mTuiChuLayout = (RelativeLayout) findViewById(R.id.hd_tuichu_layout);
//        mTuiChuLayout.setOnClickListener(this);
//        mTuiChuText = (TextView) findViewById(R.id.hd_tuichu_content);
//        initTCPopWindow();

        mJieZhiText = (TextView) findViewById(R.id.jiezhitime_content);
        mTitleText = (EditText) findViewById(R.id.hd_title);
        mRenShuText = (EditText) findViewById(R.id.hd_renshu_content);
       // mFeiYongText = (EditText) findViewById(R.id.hd_feiyong_content);
        mDescText = (EditText) findViewById(R.id.jianjie_content);
        getJianGeTime();

    }
    private void getJianGeTime(){
        HuoQuJianGeTask hqTask = new HuoQuJianGeTask();
        hqTask.addListener(createTaskListner);
        jiangeTaskId = getEatShowApp().getTaskManager().addTask(hqTask);
    }

    private TaskEventListener createTaskListner = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if(taskId == jiangeTaskId){
                mDateCha = (String) data;
            }else if(taskId==createTaskId){
                Intent tjIntent = new Intent(mContext,ChuangJianChengGongActivity.class);
                tjIntent.putExtra("FROM","CREATE");
                startActivity(tjIntent);
                finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId==createTaskId){
                createTaskId = -1;
            }else if(taskId == jiangeTaskId){
                jiangeTaskId= -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    private void initSexPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_sexlimit,null);
        view.findViewById(R.id.wu).setOnClickListener(this);
        view.findViewById(R.id.nan).setOnClickListener(this);
        view.findViewById(R.id.nv).setOnClickListener(this);
        sexPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sexPopWindow.setBackgroundDrawable(new ColorDrawable());
        sexPopWindow.setFocusable(true);
        sexPopWindow.setOutsideTouchable(true);
    }

//    private void initTCPopWindow() {
//        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_editlimit,null);
//        view.findViewById(R.id.edit_yes).setOnClickListener(this);
//        view.findViewById(R.id.edit_no).setOnClickListener(this);
//        tcPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        tcPopWindow.setBackgroundDrawable(new ColorDrawable());
//        tcPopWindow.setFocusable(true);
//        tcPopWindow.setOutsideTouchable(true);
//    }
    private void doCreate(){

        ChuangJianYueFanTask crTask = new ChuangJianYueFanTask(mTitle,city,shangquanId,mQiangDanTime,mKaishiTime,mJiezhiTime,mDesc,mRenshu,sexLimtit,"0");
        crTask.addListener(createTaskListner);
        createTaskId = getEatShowApp().getTaskManager().addTask(crTask);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.starttime_layout:
                SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");//设置日期格式
                initDateTime = df.format(new Date());
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        ChuangJianHuoDongActivity.this, initDateTime);
                         dateTimePicKDialog.dateTimePicKDialog(mStartTime);

                mStartTime.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                        mKaishiTime = mStartTime.getText().toString();
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date mdate = new Date();
                        try {
                            mdate =   sdf.parse(mKaishiTime);

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        Calendar yesterdayLate = Calendar.getInstance();
                        yesterdayLate.setTime(mdate);
                        int ss = -Integer.parseInt(mDateCha);
                        yesterdayLate.add(Calendar.HOUR_OF_DAY, ss);
                        Date yesterdayL = yesterdayLate.getTime();


                        //java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                       // SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        mJiezhiTime = sdf.format(yesterdayL);
                        mJieZhiText.setText(mJiezhiTime);
                    }
                });


                break;
            case R.id.submit_btn:
                if(checkInput()){
                    doCreate();
                }


                break;
            case R.id.qiangdantime_layout:
                SimpleDateFormat dfq = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");//设置日期格式
                initDateTime = dfq.format(new Date());
                DateTimePickDialogUtil dateTimePicKDialog2 = new DateTimePickDialogUtil(
                        ChuangJianHuoDongActivity.this, initDateTime);
                dateTimePicKDialog2.dateTimePicKDialog(mQiangDanEdit);
                mQiangDanEdit.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        mQiangDanTime = mQiangDanEdit.getText().toString();
                        PalLog.e("抢单截止时间", mQiangDanTime);

                    }
                });

                break;
            case R.id.suozaicity_layout:
                Intent cintent = new Intent(mContext, CityListActivity.class);
                startActivityForResult(cintent, 1);
                break;
            case R.id.suozaishangquan_layout:
                if(checkIsHaveCity()){
                    Intent sIntent = new Intent(mContext,ShangQuanListActivity.class);
                    sIntent.putExtra("AREANAME",city);
                    startActivityForResult(sIntent,2);
                }
                break;
//            case R.id.hd_shangjia_layout:
//                if(checkIsHaveCity() ){
//                    Intent sjIntent = new Intent(mContext,ShangJiaListActivity.class);
//                    sjIntent.putExtra("SQID",shangquanId);
//                    sjIntent.putExtra("AREANAME",city);
//                    startActivityForResult(sjIntent, 3);
//                }
//                break;
            case R.id.hd_xingbie_layout:
                sexPopWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
                break;
            case R.id.wu:
                mSexText.setText("无");
                sexLimtit = "0";
                sexPopWindow.dismiss();
                break;
            case R.id.nan:
                mSexText.setText(R.string.xiannanxing);
                sexLimtit = "1";
                sexPopWindow.dismiss();
                break;
            case R.id.nv:
                mSexText.setText(R.string.xiannvxing);
                sexLimtit = "2";
                sexPopWindow.dismiss();
                break;
//            case R.id.hd_tuichu_layout:
//                tcPopWindow.showAtLocation(v,Gravity.BOTTOM,0,0);
//                break;
//            case R.id.edit_yes:
//                mTuiChuText.setText(R.string.edityes);
//                tuichu = "1";
//                tcPopWindow.dismiss();
//                break;
//            case R.id.edit_no:
//                mTuiChuText.setText(R.string.editno);
//                tuichu = "0";
//                tcPopWindow.dismiss();
//                break;

//            case  R.id.hd_caipin_layout:
//                if(checkIsHaveSeller()){
//                    Intent cpInent = new Intent(mContext, CaiPinListActivity.class);
//                    cpInent.putExtra("BUSINESSID",shangjiaId);
//                    cpInent.putExtra("FROM",2);
//                    if (!ViewUtil.isNull(selectCaipin)){
//                        cpInent.putExtra("SELECT_CAIPIN",selectCaipin);
//                    }
//                    startActivityForResult(cpInent,4);
//                }
//
//                break;
        }
    }

    private boolean checkIsHaveCity() {

        if (TextUtils.isEmpty(city)) {
            Toast.makeText(mContext, R.string.choose_city, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private boolean checkIsHaveSQ() {

        if (TextUtils.isEmpty(shangquanId)) {
            Toast.makeText(mContext, R.string.choose_shangquan, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

//    private boolean checkIsHaveSeller(){
//        if (TextUtils.isEmpty(shangjia)) {
//            Toast.makeText(mContext, R.string.choose_shangjia, Toast.LENGTH_SHORT)
//                    .show();
//            return false;
//        }
//        return true;
//    }

    private boolean checkInput(){
        mTitle = mTitleText.getText().toString();
        mRenshu = mRenShuText.getText().toString();
      //  mFeiyong = mFeiYongText.getText().toString();
        mDesc = mDescText.getText().toString();
//        mPsw = MD5.digest(pswEdit.getText().toString());
        if (TextUtils.isEmpty(mTitle)) {
            Toast.makeText(mContext, "请输入活动标题", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }else if(TextUtils.isEmpty(mKaishiTime)){
            Toast.makeText(mContext, "请先选择开始时间", Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else if (TextUtils.isEmpty(city)) {
            Toast.makeText(mContext, "请先选择城市", Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else if(TextUtils.isEmpty(mRenshu)|| Integer.parseInt(mRenshu)<1){
            Toast.makeText(mContext, "请输入人数限制", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }else if(TextUtils.isEmpty(sexLimtit)){
            Toast.makeText(mContext, "请选择性别限制", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
//        else if(TextUtils.isEmpty(mFeiyong)){
//            Toast.makeText(mContext, "请输入人均费用", Toast.LENGTH_SHORT)
//                    .show();
//            return false;
//        }else if (ViewUtil.isNull(selectCaipin)){
//            Toast.makeText(mContext, "请选择菜品", Toast.LENGTH_SHORT)
//                    .show();
//        }else if (ViewUtil.isNull(shangjia)){
//            Toast.makeText(mContext, "请选择商家", Toast.LENGTH_SHORT)
//                    .show();
//        }
//        else if(TextUtils.isEmpty(tuichu)){
//            Toast.makeText(mContext, "请选择退出方式", Toast.LENGTH_SHORT)
//                    .show();
//            return false;
//        }
        else if(TextUtils.isEmpty(mDesc)){
            Toast.makeText(mContext, "请输入活动简介", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // String
        if(requestCode==1){
            if (data != null) {
                city = data.getExtras().getString("areaName");
                mCityText.setText(city);

            }
        }else if(requestCode==2){
            if(data != null) {
                shangquan = data.getExtras().getString("SQNAME");
                shangquanId = data.getExtras().getString("SQID");
                mShangQuanText.setText(shangquan);

            }
        }
//        else if(requestCode==3){
//            if(data != null) {
//                shangjia = data.getExtras().getString("SJNAME");
//                shangjiaId = data.getExtras().getString("SJID");
//                mShangjiaText.setText(shangjia);
//            }
//        }else if (requestCode ==4){
//            if (data != null){
//                mCaipinString = data.getStringExtra("SELECT_ALREADY");
//                selectCaipin = data.getStringExtra("SELECTCAIPIN");
//                PalLog.e("选中的菜品",selectCaipin);
//                mCaipinText.setText(mCaipinString);
//            }
//        }

    }

}
